﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Kinect;
using Microsoft.Kinect.Toolkit;
using Microsoft.Speech;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
using System.Collections;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Windows.Markup;
using System.Windows.Threading;
using System.Threading;
using System.Net.Mail;
using System.Configuration;
using System.Net;
using System.Xml;
using System.Web;
using System.Text.RegularExpressions;

namespace ImHere
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        // used by the file and mail constructor to name files and attach a bitly
        public int counter = 1;
        public string yourName = "";
        public string lastFile = "";
        public string bitLy = "";
        public string pType = "";

        private KinectSensor kinectSensor = null;
        private MultiSourceFrameReader _reader = null;

        // singleton for the green screener, see BackgroundFixer.cs for more details
        private BackgroundRemovalTool _bTool;

        private KinectAudioStream convertStream = null;
        private SpeechRecognitionEngine speechEngine = null;

        private ColorFrameReader colorFrameReader = null;
        private BitmapImage colorBitmap = null;
        
        private string statusText = null;

        // currently unused email verification scheme
        public static bool validEmail(string email)
        {
            string expression;
            expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
            if (Regex.IsMatch(email, expression))
            {
                if (Regex.Replace(email, expression, string.Empty).Length == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            camera.Visibility = Visibility.Hidden;
            this.kinectSensor = KinectSensor.GetDefault();
            if (this.kinectSensor != null)
            {
                this.kinectSensor.Open();
                _bTool = new BackgroundRemovalTool(kinectSensor.CoordinateMapper);
                _reader = kinectSensor.OpenMultiSourceFrameReader(FrameSourceTypes.Color | FrameSourceTypes.Depth | FrameSourceTypes.BodyIndex);
                _reader.MultiSourceFrameArrived += _reader_MultiSourceFrameArrived;
                FrameDescription colorFrameDescription = this.kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);

                IReadOnlyList<AudioBeam> audioBeamList = this.kinectSensor.AudioSource.AudioBeams;
                System.IO.Stream audioStream = audioBeamList[0].OpenInputStream();
                this.convertStream = new KinectAudioStream(audioStream);
                this.kinectSensor.IsAvailableChanged += kinectSensor_IsAvailableChanged;

                // Check executable bin for values of Azure user and Azure password
                Configuration config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
                AzUser = config.AppSettings.Settings["azureUser"].Value;
                AzPass = config.AppSettings.Settings["azurePass"].Value;

                ThreadPool.QueueUserWorkItem(delegate
                {
                    this.StatusText = Properties.Resources.StartUpOne;
                    Thread.Sleep(3000);
                    this.StatusText = Properties.Resources.StartUpTwo;
                    Thread.Sleep(3000);
                    this.StatusText = Properties.Resources.StartUpThree;
                });
                this.DataContext = this;
            }
            else
            {
                return;
            }

            RecognizerInfo ri = TryGetKinectRecognizer();

            if (ri != null)
            {
                
                this.speechEngine = new SpeechRecognitionEngine(ri.Id);
                var commands = new Choices();
                commands.Add(new SemanticResultValue("here", "HERE"));
                commands.Add(new SemanticResultValue("beach", "BEACH"));
                commands.Add(new SemanticResultValue("office", "OFFICE"));
                commands.Add(new SemanticResultValue("coder camps", "CODER CAMPS"));
                commands.Add(new SemanticResultValue("developer", "DEVELOPER"));
                commands.Add(new SemanticResultValue("hiring partner", "HIRING PARTNER"));
                commands.Add(new SemanticResultValue("instructor", "INSTRUCTOR"));
                commands.Add(new SemanticResultValue("student", "STUDENT"));
                commands.Add(new SemanticResultValue("ready", "READY"));
                commands.Add(new SemanticResultValue("attendance", "ATTENDANCE"));
                commands.Add(new SemanticResultValue("photograph", "PHOTOGRAPH"));
                commands.Add(new SemanticResultValue("good", "GOOD"));
                commands.Add(new SemanticResultValue("save", "SAVE"));
                commands.Add(new SemanticResultValue("guest", "GUEST"));

                var gb = new GrammarBuilder { Culture = ri.Culture };
                gb.Append(commands);
                var g = new Grammar(gb);
                this.speechEngine.LoadGrammar(g);

                this.speechEngine.SpeechRecognized += this.SpeechRecognized;
                this.speechEngine.SpeechRecognitionRejected += this.SpeechRejected;
                this.convertStream.SpeechActive = true;
                this.speechEngine.SetInputToAudioStream(this.convertStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
                this.speechEngine.RecognizeAsync(RecognizeMode.Multiple);
            }
            else
            {
                
            }
        }
        private void SpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
        {
            string rejectHolder = e.Result.Semantics.ToString();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public ImageSource ImageSource
        {
            get { return this.colorBitmap; }
        }
        private string imgSource = null;
        
        // binding zone for azure username
        private string azUser = null;
        public string AzUser
        {
            get { return this.azUser; }
            set
            {
                if (this.azUser != value)
                {
                    this.azUser = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("AzUser"));
                    }
                }
            }
        }

        // binding zone for azure password
        private string azPass = null;
        public string AzPass
        {
            get { return this.azPass; }
            set
            {
                if (this.azPass != value)
                {
                    this.azPass = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("AzPass"));
                    }
                }
            }
        }

        // binding zone for student names if being used as an attendance tracker
        private string myName = null;
        public string MyName
        {
            get { return this.myName; }
            set
            {
                if (this.myName != value)
                {
                    this.myName = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("MyName"));
                    }
                }
            }
        }

        // binding zone for emails if being used as a photobooth
        private string email = null;
        public string Email
        {
            get { return this.email; }
            set
            {
                if (this.email != value)
                {
                    this.email = value;
                    validEmail(email);
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("Email"));
                    }
                }
            }
        }
        public string ImgSource
        {
            get { return this.imgSource; }
            set
            {
                if (this.imgSource != value)
                {
                    this.imgSource = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("ImgSource"));
                    }
                }
            }
        }

        private string picSource = null;
        public string PicSource
        {
            get { return this.picSource; }
            set
            {
                if (this.picSource != value)
                {
                    this.picSource = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("PicSource"));
                    }
                }
            }
        }

        public string StatusText
        {
            get { return this.statusText; }
            set
            {
                if (this.statusText != value)
                {
                    this.statusText = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
                    }
                }
            }
        }

        private enum Actions
        {
            // If i want those verbs to become an event action of some kind, they go here for use elsewhere.
        }

        private static RecognizerInfo TryGetKinectRecognizer()
        {
            IEnumerable<RecognizerInfo> recognizers;

            try
            {
                recognizers = SpeechRecognitionEngine.InstalledRecognizers();
            }
            catch (COMException)
            {
                return null;
            }
            foreach (RecognizerInfo recognizer in recognizers)
            {
                string value;
                recognizer.AdditionalInfo.TryGetValue("Kinect", out value);
                if ("True".Equals(value, StringComparison.OrdinalIgnoreCase) && "en-US".Equals(recognizer.Culture.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return recognizer;
                }
            }
            return null;
        }

        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            // on closing of window, dispose all stuff from memory and close the kinect down
            if (this.convertStream != null)
            {
                this.convertStream.SpeechActive = false;
            }

            if (this.speechEngine != null)
            {
                this.speechEngine.SpeechRecognized -= this.SpeechRecognized;
                this.speechEngine.SpeechRecognitionRejected -= this.SpeechRejected;
                this.speechEngine.RecognizeAsyncStop();
            }

            if (this.colorFrameReader != null)
            {
                this.colorFrameReader.Dispose();
                this.colorFrameReader = null;
            }

            if (this._reader != null)
            {
                this._reader.Dispose();
                this._reader = null;
            }

            if (this.kinectSensor != null)
            {
                this.kinectSensor.Close();
                this.kinectSensor = null;
            }
        }
        
        private void Screenshot_click(object sender, RoutedEventArgs e)
        {
            if (Email != null) { 
            int colorWidth = this.colorBitmap.PixelWidth;
            int colorHeight = this.colorBitmap.PixelHeight;

            var renderBitmap = new RenderTargetBitmap(colorWidth, colorHeight, 96.0, 96.0, PixelFormats.Pbgra32);

            var dv = new DrawingVisual();
            using (var dc = dv.RenderOpen())
            {
                Image bi = new Image();
                bi.Source = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                var backdropBrush = new ImageBrush();
                backdropBrush.ImageSource = bi.Source;
                dc.DrawRectangle(backdropBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight)));

                var colorBrush = new VisualBrush(camera);
                dc.DrawRectangle(colorBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight)));
            }

            renderBitmap.Render(dv);

            Guid id = Guid.NewGuid();
            var yourGuid = Convert.ToBase64String(id.ToByteArray());
            var credentials = new StorageCredentials(AzUser, AzPass);
            var client = new CloudBlobClient(new Uri("https://" + AzUser + ".blob.core.windows.net/"), credentials);
            var newContainer = System.DateTime.Now.ToString("yyyy-MM-dd");
            var container = client.GetContainerReference(newContainer);
            container.CreateIfNotExists();
            if (this.colorBitmap != null)
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                string date = System.DateTime.Now.ToString("//yyyy-MM-dd", CultureInfo.CurrentUICulture.DateTimeFormat);
                string time = System.DateTime.Now.ToString("hh'-'mm", CultureInfo.CurrentUICulture.DateTimeFormat);
                string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                Directory.CreateDirectory(myPhotos + date);
                string path = Path.Combine(myPhotos + date, counter + "-" + yourName + "-" + time + ".png");
                lastFile = path;

                try
                {
                    using (FileStream fs = new FileStream(path, FileMode.Create))
                    {
                        encoder.Save(fs);
                    }
                    using (var fileStream = System.IO.File.OpenRead(path))
                    {
                        var blockBlob = container.GetBlockBlobReference(counter + ".png");
                        blockBlob.Properties.ContentType = "image/png";
                        blockBlob.UploadFromStream(fileStream);
                    }
                    string urlToShorten = "https://" + AzUser + ".blob.core.windows.net/" + date + "/" + counter + ".png";
                    XmlDocument xmlDoc = new XmlDocument();
                    WebRequest request = WebRequest.Create("http://api.bitly.com/v3/shorten");
                    byte[] data = Encoding.UTF8.GetBytes(string.Format("login={0}&apikey={1}&longUrl={2}&format={3}", "abethel1986", "R_a4a433eaf6a741898d490242c38aa758", HttpUtility.UrlEncode(urlToShorten), "xml"));
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;
                    using (Stream ds = request.GetRequestStream())
                    {
                        ds.Write(data, 0, data.Length);
                    }
                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            xmlDoc.LoadXml(sr.ReadToEnd());
                        }
                    }
                    bitLy = xmlDoc.GetElementsByTagName("url")[0].InnerText;

                    this.kinectSensor.Close();
                    camera.Source = null;
                    this.ImgSource = null;
                    this.PicSource = path;
                    this.StatusText = string.Format(Properties.Resources.PhotoTaken);

                    if (Email != null)
                    {
                        MailMessage message = new MailMessage();
                        message.From = new MailAddress("youremail@address.com");
                        try
                        {
                            message.To.Add(Email);
                            message.Subject = "I'm Here";
                            message.Body = "Thanks for coming to Coder Camps Demo Day, and thanks for getting your picture taken with us!  Your photo is attached!  You can link the photo to your friends, too.  Send them this link: " + bitLy + " - Andrew Bethel (LinkedIn: https://www.linkedin.com/pub/andrew-bethel/a8/849/18)";
                            message.Attachments.Add(new Attachment(path));
                            NetworkCredential auth = new NetworkCredential("youremail@address.com", "mypass");
                            SmtpClient mailClient = new SmtpClient("smtp-mail.outlook.com", 587);
                            mailClient.Credentials = auth;
                            mailClient.EnableSsl = true;
                            mailClient.Send(message);
                        }
                        catch
                        {
                            this.StatusText = string.Format(Properties.Resources.EmailError, bitLy);
                        }
                    }
                }
                catch (IOException)
                {
                    //this.StatusText = string.Format(Properties.Resources.FailedScreenshotStatusTextFormat, path);
                }
                ThreadPool.QueueUserWorkItem(delegate
                {
                    if (this.StatusText == string.Format(Properties.Resources.EmailError, bitLy))
                    {
                        this.StatusText = string.Format(Properties.Resources.EmailError, bitLy);
                        counter++;
                        Thread.Sleep(20000);
                        this.PicSource = null;
                        this.Email = null;
                        this.StatusText = string.Format(Properties.Resources.EnterEmail);
                        this.kinectSensor.Open();
                        Thread.Sleep(8000);
                    }
                    else
                    {
                        this.StatusText = string.Format(Properties.Resources.email, Email);
                        Thread.Sleep(5000);
                        this.StatusText = string.Format(Properties.Resources.EmailSuccessGuid, bitLy);
                        counter++;
                        Thread.Sleep(15000);
                        this.PicSource = null;
                        this.Email = null;
                        this.StatusText = string.Format(Properties.Resources.EnterEmail);
                        this.kinectSensor.Open();
                        Thread.Sleep(8000);
                    }
                });
                camera.Visibility = Visibility.Hidden;
            }
            }
            // If running as attendance, will only upload to azure entered in by instructor
            if (MyName != null)
            {
                int colorWidth = this.colorBitmap.PixelWidth;
                int colorHeight = this.colorBitmap.PixelHeight;

                var renderBitmap = new RenderTargetBitmap(colorWidth, colorHeight, 96.0, 96.0, PixelFormats.Pbgra32);

                var dv = new DrawingVisual();
                using (var dc = dv.RenderOpen())
                {
                    Image bi = new Image();
                    bi.Source = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                    var backdropBrush = new ImageBrush();
                    backdropBrush.ImageSource = bi.Source;
                    dc.DrawRectangle(backdropBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight)));

                    var colorBrush = new VisualBrush(camera);
                    dc.DrawRectangle(colorBrush, null, new Rect(new Point(), new Size(colorWidth, colorHeight)));
                }

                renderBitmap.Render(dv);

                Guid id = Guid.NewGuid();
                var yourGuid = Convert.ToBase64String(id.ToByteArray());
                var credentials = new StorageCredentials(AzUser, AzPass); // user entered azure information
                var client = new CloudBlobClient(new Uri("https://" + AzUser +".blob.core.windows.net/"), credentials);
                var newContainer = System.DateTime.Now.ToString("yyyy-MM-dd"); // container name in azure storage will be the current date, year month and day
                var container = client.GetContainerReference(newContainer);
                container.CreateIfNotExists();
                if (this.colorBitmap != null)
                {
                    BitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    string date = System.DateTime.Now.ToString("//yyyy-MM-dd", CultureInfo.CurrentUICulture.DateTimeFormat);
                    string time = System.DateTime.Now.ToString("hh'-'mm", CultureInfo.CurrentUICulture.DateTimeFormat);
                    string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                    Directory.CreateDirectory(myPhotos + date);
                    string path = Path.Combine(myPhotos + date, counter + "-" + pType + "-" + MyName + "-" + time + ".png");
                    lastFile = path;

                    try
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create))
                        {
                            encoder.Save(fs);
                        }
                        using (var fileStream = System.IO.File.OpenRead(path))
                        {
                            var blockBlob = container.GetBlockBlobReference(counter + "-" + pType + "-" + MyName + ".png");
                            blockBlob.Properties.ContentType = "image/png";
                            blockBlob.UploadFromStream(fileStream);
                        }
                    }
                    catch (IOException)
                    {
                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            this.StatusText = Properties.Resources.UploadError;
                            Thread.Sleep(10000);
                            Application.Current.Shutdown();
                        });
                    }
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        this.PicSource = null;
                        this.MyName = null;
                        this.StatusText = Properties.Resources.YourName;
                        Thread.Sleep(10000);
                        this.kinectSensor.Open();
                    });
                    camera.Visibility = Visibility.Hidden;
                }
            }
            
        }
        
        private void SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            const double ConfidenceThreshold = 0.8;
            SemanticValue semantics = e.Result.Semantics;
            RecognitionResult result = e.Result;
            if (e.Result.Confidence >= ConfidenceThreshold)
            {
                switch (e.Result.Semantics.Value.ToString())
                {
                    case "SAVE":
                        {
                            if (this.StatusText == Properties.Resources.InitRepeat)
                            {
                                // Erase existing values, prepare to accept new ones
                                AzPass = null;
                                AzUser = null;
                                this.StatusText = Properties.Resources.InitOne;
                                azuser.Visibility = Visibility.Visible;
                                break;
                            }
                            if (this.StatusText == Properties.Resources.InitTwo)
                            {
                                // AzUser and AzPass are saved to the .exe.config file, not to the app.config in this assembly.  Thus, user information is only ever saved locally to the user's computer.
                                Configuration config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
                                config.AppSettings.Settings["azureUser"].Value = AzUser;
                                config.AppSettings.Settings["azurePass"].Value = AzPass;
                                config.Save(ConfigurationSaveMode.Modified);
                                azpass.Visibility = Visibility.Hidden;
                                this.StatusText = Properties.Resources.AttPerType;
                            }
                            break;
                        }
                    case "GOOD":
                        {
                            if (this.StatusText == Properties.Resources.InitRepeat)
                            {
                                this.StatusText = Properties.Resources.YourName;
                                break;
                            }
                            if (this.StatusText == Properties.Resources.InitOne)
                            {
                                azuser.Visibility = Visibility.Hidden;
                                azpass.Visibility = Visibility.Visible;
                                this.StatusText = Properties.Resources.InitTwo;
                            }
                        }
                        break;
                    case "ATTENDANCE":
                        if (this.StatusText == Properties.Resources.StartUpThree)
                        {
                            this.StatusText = Properties.Resources.InitRepeat;
                        }
                        else
                        {

                        }
                        break;
                    case "PHOTOGRAPH":
                        if (this.StatusText == Properties.Resources.StartUpThree)
                        {
                            emailspace.Visibility = Visibility.Visible;
                            this.StatusText = Properties.Resources.EnterEmail;
                        }
                        else
                        {

                        }
                        break;
                    case "READY":
                        if (this.StatusText == Properties.Resources.EnterEmail)
                        {
                            this.StatusText = Properties.Resources.PersonType;
                            camera.Visibility = Visibility.Visible;
                            break;
                        }
                        if (this.StatusText == string.Format(Properties.Resources.AttPerTypeResponse, "Student") || this.StatusText == string.Format(Properties.Resources.AttPerTypeResponse, "Guest"))
                        {
                            // If being used as an attendance app, to make sure it can happen quickly and class can begin, just use a preset background and enable say here
                            namespot.Visibility = Visibility.Hidden;
                            camera.Visibility = Visibility.Visible;
                            this.ImgSource = "/Images/backdrop-project.jpg";
                            this.colorBitmap = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                            this.PropertyChanged(this, new PropertyChangedEventArgs("colorBitmap"));
                            this.StatusText = Properties.Resources.SayHere;
                        }
                        break;

                    case "HERE":
                        if (this.StatusText == string.Format(Properties.Resources.SayHere))
                        {
                            ButtonAutomationPeer peer = new ButtonAutomationPeer(SnapShot);
                            IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                            invokeProv.Invoke();
                        } 
                        else
                        {
                            
                        }
                        break;
                    case "CODER CAMPS":
                        if (this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Developer") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Instructor") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Student") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Hiring Partner"))
                        {
                            this.ImgSource = "/Images/backdrop-project.jpg";
                            this.colorBitmap = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                            this.PropertyChanged(this, new PropertyChangedEventArgs("colorBitmap"));
                            this.StatusText = string.Format(Properties.Resources.BackgroundChanged, "star walk!");
                            ThreadPool.QueueUserWorkItem(delegate
                            {
                                Thread.Sleep(4000);
                                this.StatusText = Properties.Resources.EmailCorrect;
                                Thread.Sleep(3000);
                                this.StatusText = string.Format(Properties.Resources.SayHere);
                            });
                        }
                        else
                        {

                        }
                        break;
                    case "BEACH":
                        if (this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Developer") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Instructor") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Student") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Hiring Partner"))
                        {
                            this.ImgSource = "/Images/beach.jpg";
                            this.colorBitmap = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                            this.PropertyChanged(this, new PropertyChangedEventArgs("colorBitmap"));
                            this.StatusText = string.Format(Properties.Resources.BackgroundChanged, "beach!");
                            ThreadPool.QueueUserWorkItem(delegate
                            {
                                Thread.Sleep(4000);
                                this.StatusText = Properties.Resources.EmailCorrect;
                                Thread.Sleep(3000);
                                this.StatusText = string.Format(Properties.Resources.SayHere);
                            });
                        }
                        else
                        {

                        }
                        break;
                    case "OFFICE":
                        if (this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Developer") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Instructor") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Student") || this.StatusText == string.Format(Properties.Resources.PersonTypeResponse, "Hiring Partner"))
                        {
                            this.ImgSource = "/Images/office.jpg";
                            this.colorBitmap = new BitmapImage(new Uri("pack://application:,,," + ImgSource));
                            this.PropertyChanged(this, new PropertyChangedEventArgs("colorBitmap"));
                            this.StatusText = string.Format(Properties.Resources.BackgroundChanged, "office!");
                            ThreadPool.QueueUserWorkItem(delegate
                            {
                                Thread.Sleep(4000);
                                this.StatusText = Properties.Resources.EmailCorrect;
                                Thread.Sleep(3000);
                                this.StatusText = string.Format(Properties.Resources.SayHere);
                            });
                        }
                        else
                        {

                        }
                        break;
                    case "DEVELOPER":
                        if (this.StatusText == string.Format(Properties.Resources.PersonType))
                        {
                            this.StatusText = string.Format(Properties.Resources.PersonTypeResponse, "Developer");
                            pType = "Developer";
                        }
                        else
                        {

                        }
                        break;
                    case "INSTRUCTOR":
                        if (this.StatusText == string.Format(Properties.Resources.PersonType))
                        {
                            this.StatusText = string.Format(Properties.Resources.PersonTypeResponse, "Instructor");
                            pType = "Instructor";
                        } 
                        else
                        {

                        }
                        break;
                    case "HIRING PARTNER":
                        if (this.StatusText == string.Format(Properties.Resources.PersonType))
                        {
                            this.StatusText = string.Format(Properties.Resources.PersonTypeResponse, "Hiring Partner");
                            pType = "HiringPartner";
                        }
                        else
                        {

                        }
                        break;
                    case "STUDENT":
                        if (this.StatusText == string.Format(Properties.Resources.PersonType))
                        {
                            this.StatusText = string.Format(Properties.Resources.PersonTypeResponse, "Student");
                            yourName = "Student";
                            break;
                        }
                        if (this.StatusText == Properties.Resources.AttPerType)
                        {
                            this.StatusText = string.Format(Properties.Resources.AttPerTypeResponse, "Student");
                            pType = "Student";
                            namespot.Visibility = Visibility.Visible;
                        }
                        break;
                    case "GUEST":
                        if (this.StatusText == Properties.Resources.AttPerType)
                        {
                            this.StatusText = string.Format(Properties.Resources.AttPerTypeResponse, "Guest");
                            pType = "Guest";
                            namespot.Visibility = Visibility.Visible;
                        }
                        break;
                }


            }
        }
        void _reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            var reference = e.FrameReference.AcquireFrame();

            using (var colorFrame = reference.ColorFrameReference.AcquireFrame())
            using (var depthFrame = reference.DepthFrameReference.AcquireFrame())
            using (var bodyIndexFrame = reference.BodyIndexFrameReference.AcquireFrame())
            {
                if (colorFrame != null && depthFrame != null && bodyIndexFrame != null)
                {
                    camera.Source = _bTool.GreenScreen(colorFrame, depthFrame, bodyIndexFrame);
                }
            }
                
        }

        private void kinectSensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e)
        {
            //this.statusText = this.kinectSensor.IsAvailable ? Properties.Resources.PersonType : Properties.Resources.PersonType;
        }
    }
}
